package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go_api/pkg/logger"
	"time"
)

// GinLogger 自定义 Gin 日志中间件
func GinLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path

		// 处理请求
		c.Next()
		// 计算时间间隔
		duration := time.Since(start)
		//转换为s单位
		seconds := duration.Seconds()
		//设置输出格式
		fields := logrus.Fields{
			"status":     c.Writer.Status(),
			"method":     c.Request.Method,
			"path":       path,
			"ip":         c.ClientIP(),
			"latency":    seconds,
			"user_agent": c.Request.UserAgent(),
		}
		// 记录日志
		logger.WithFieldsInfo(fields)

	}
}
